package com.atguigu.chapter07.state;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/20 11:40
 */
public class Flink07_State_KV_Aggregate {
    
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        env
            .socketTextStream("hadoop162", 9999)
            .map(value -> {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
                
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                
                private AggregatingState<WaterSensor, Double> avgState;
                
                class AvgAcc {
                    Integer sumVc = 0;
                    Long count = 0L;
                    
                    public Double getAvg(){
                        return sumVc * 1.0 / count;
                    }
                }
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    avgState = getRuntimeContext()
                        .getAggregatingState(new AggregatingStateDescriptor<WaterSensor, AvgAcc, Double>(
                            "avgState",
                            new AggregateFunction<WaterSensor, AvgAcc, Double>() {
                                @Override
                                public AvgAcc createAccumulator() {
                                    return new AvgAcc();
                                }
                                
                                @Override
                                public AvgAcc add(WaterSensor value, AvgAcc acc) {
                                    acc.sumVc += value.getVc();
                                    acc.count += 1;
                                    return acc;
                                }
                                
                                @Override
                                public Double getResult(AvgAcc acc) {
                                    return acc.getAvg();
                                }
                                
                                @Override
                                public AvgAcc merge(AvgAcc a, AvgAcc b) {
                                    a.sumVc += b.sumVc;
                                    a.count += b.count;
                                    return a;
                                }
                            },
                            AvgAcc.class
                        ));
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    avgState.add(value);
                    
                    
                    out.collect(ctx.getCurrentKey() + " 的平均水位是: " + avgState.get());
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

